package com.wy.business.market.home.services;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.pojos.TSysFunction;
import com.wy.framework.pojos.TSysUserselectedfunction;
import com.wy.framework.services.AbstractBaseService;

/**
 * 项目名称：openportal
 * 类名称：AppsManageService
 * 类描述：滚动轮播(banner)
 * 创建人：张旭星
 * 创建时间：2015-12-30 下午2:05:29
 * 修改人：张旭星
 * 修改时间：2015-12-30 下午2:05:29
 * 版本信息：@version 1.0
 * Copyright (c) 2015万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
@Service
public class AppsManageService extends AbstractBaseService {

	private static final char[] object = null;
	private static Logger logger = LoggerFactory
			.getLogger(AppsManageService.class);

	@SuppressWarnings({ "unchecked"})
	public void updateUserAppsSort(String userId,String functionId,int sort) throws ErrorSqlException{
		List<TSysUserselectedfunction> list = (List<TSysUserselectedfunction>) dataBaseDao.getHibernateTemplate().find(" from TSysUserselectedfunction t where t.functionId=? and t.userId=? ", new Object[]{functionId,userId});
		TSysUserselectedfunction tSysUserselectedfunction = (list==null||list.size()==0||list.get(0)==null)?null:(TSysUserselectedfunction)list.get(0);
		if(tSysUserselectedfunction!=null){
			//向后移动
			if (tSysUserselectedfunction.getSelfSort() < sort) {
				list=(List<TSysUserselectedfunction>) dataBaseDao.getHibernateTemplate().find("from TSysUserselectedfunction f where f.userId=? and f.selfSort > ? and f.selfSort < ?", new Object[]{userId,tSysUserselectedfunction.getSelfSort(),sort + 1});
				//给中间的应用排序-1
				for (TSysUserselectedfunction object : list) {
					object.setSelfSort(object.getSelfSort()-1);
					dataBaseDao.update(object);
				}
			}
			//向前移动
			else if(tSysUserselectedfunction.getSelfSort() > sort) {
				list=(List<TSysUserselectedfunction>) dataBaseDao.getHibernateTemplate().find("from TSysUserselectedfunction f where f.userId=? and f.selfSort > ? and f.selfSort < ?", new Object[]{userId,sort - 1,tSysUserselectedfunction.getSelfSort()});
				//给中间的应用排序+1
				for (TSysUserselectedfunction object : list) {
					object.setSelfSort(object.getSelfSort()+1);
					dataBaseDao.update(object);
				}
				
			}
			tSysUserselectedfunction.setSelfSort(sort);
			dataBaseDao.update(tSysUserselectedfunction);
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public void deleteUserApp(String functionId,String userId) throws ErrorSqlException{
		int sort = 0;
		List<TSysUserselectedfunction> list = (List<TSysUserselectedfunction>) dataBaseDao.getHibernateTemplate().find(" from TSysUserselectedfunction t where t.functionId=? and t.userId=? ", new Object[]{functionId,userId});
		TSysUserselectedfunction tSysUserselectedfunction = (list==null||list.size()==0||list.get(0)==null)?null:(TSysUserselectedfunction)list.get(0);
		if(tSysUserselectedfunction!=null){
			sort = tSysUserselectedfunction.getSelfSort();
			dataBaseDao.delete(tSysUserselectedfunction);
		}
		
		//对之后的应用重新排序
		list = (List<TSysUserselectedfunction>) dataBaseDao.getHibernateTemplate().find(" from TSysUserselectedfunction t where t.userId=? and t.selfSort >? ", new Object[]{userId,sort});
		for (TSysUserselectedfunction functionNeedMove : list) {
			functionNeedMove.setSelfSort(functionNeedMove.getSelfSort()-1);
			dataBaseDao.update(functionNeedMove);
		}
	}
	
	public void updateFunctionViews(String functionId) throws ErrorSqlException{
		TSysFunction function=(TSysFunction)dataBaseDao.load(TSysFunction.class, functionId);
		function.setViewdTimes(function.getViewdTimes()+1);
		dataBaseDao.update(function);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List updateAppListSync(String userId, String functionIds) throws ErrorSqlException {
		List params = new ArrayList();
		params.add(userId);
		int i = dataBaseDao.queryForInt("t_sys_userselectedfunction.exists", params);
		//该用户从未记录过
		if(i==0){
			String arr[] = StringUtils.split(functionIds, ",");
			for(int j=0;j<arr.length;j++){
				TSysUserselectedfunction tSysUserselectedfunction = new TSysUserselectedfunction();
				tSysUserselectedfunction.setFunctionId(arr[j]);
				tSysUserselectedfunction.setIsAvailable("1");
				tSysUserselectedfunction.setOperatorAccount(userId);
				tSysUserselectedfunction.setOperatorName(userId);
				tSysUserselectedfunction.setSelfClassification("");
				tSysUserselectedfunction.setShowHome("1");
				tSysUserselectedfunction.setSelfSort(j);
				tSysUserselectedfunction.setUpdateTime(new Timestamp(new Date().getTime()));
				tSysUserselectedfunction.setUserFunctionId(UUID.randomUUID().toString());
				tSysUserselectedfunction.setUserId(userId);
				dataBaseDao.save(tSysUserselectedfunction);
			}
			return new ArrayList();
		}
//		该用户登录记录过,则下载之前的列表
		else{
			return dataBaseDao.queryForList("t_sys_userselectedfunction.getByUserId", params);
		}
	}

	public void addApp(String functionId, String userId) throws ErrorSqlException {
		List params = new ArrayList();
		params.add(userId);
		int sort = dataBaseDao.queryForInt("t_sys_userselectedfunction.maxSort", params);
		
		TSysUserselectedfunction tSysUserselectedfunction = new TSysUserselectedfunction();
		tSysUserselectedfunction.setFunctionId(functionId);
		tSysUserselectedfunction.setIsAvailable("1");
		tSysUserselectedfunction.setOperatorAccount(userId);
		tSysUserselectedfunction.setOperatorName(userId);
		tSysUserselectedfunction.setSelfClassification("");
		tSysUserselectedfunction.setShowHome("1");
		tSysUserselectedfunction.setSelfSort(sort);
		tSysUserselectedfunction.setUpdateTime(new Timestamp(new Date().getTime()));
		tSysUserselectedfunction.setUserFunctionId(UUID.randomUUID().toString());
		tSysUserselectedfunction.setUserId(userId);
		dataBaseDao.save(tSysUserselectedfunction);
	}
	
}
